from django_redis import get_redis_connection
from rest_framework import serializers



from apps.question.models import Label, Question, Reply

from apps.leadnews.models import Article
from apps.recruit.serializers.EnterpriseSerializer import EnterpriseModelSerializer
from . models import User
import re
from rest_framework_jwt.settings import api_settings

class UserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    token = serializers.CharField(label='JWT token', read_only=True)
    password = serializers.CharField(label='密码', write_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'sms_code', 'mobile', 'token', 'avatar']
        extra_kwargs = {
            'password': {
                'write_only': True,
                'min_length': 6,
                'max_length': 16,
                'error_messages': {
                    'min_length': '最小长度为6',
                    'max_length': '最大长度为16'
                }
            }
        }

    def validate_mobile(self, value):
        # 手机号格式
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')

        # 手机号是否注册
        count = User.objects.filter(mobile=value).count()
        if count != 0:
            raise serializers.ValidationError('手机号已注册')
        return value

    def validate_allow(self, value):
        # 用户协议
        if value != 'true':
            raise serializers.ValidationError('请同意协议')
        return value

    def validate(self, attrs):
        # 短信验证码是否正确
        redis_conn = get_redis_connection('verify_codes')

        mobile = attrs['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')
        sms_code = attrs['sms_code']

        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')
        return attrs

    def create(self, validated_data):
        del validated_data['sms_code']
        # 创建新用户
        user = User.objects.create_user(**validated_data)
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user

from rest_framework_jwt.serializers import JSONWebTokenSerializer,jwt_payload_handler,jwt_encode_handler
from django.contrib.auth import authenticate
from django.utils.translation import ugettext as _

class AdminJSONWebTokenSerializer(JSONWebTokenSerializer):
    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }
        #   多账号登录
        if re.match(r'^1[3-9][0-9]{9}$', credentials['username']):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'
        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)

                return {
                    'token': jwt_encode_handler(payload),
                    'user': user
                }
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            msg = _('Must include "{username_field}" and "password".')
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)


class LabelsModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = '__all__'

class QuestionAnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Reply
        fields = '__all__'

class CollectSerializer(serializers.ModelSerializer):
    collected_users = serializers.StringRelatedField()

    class Meta:
        model = Article
        fields = '__all__'





import datetime
class UserInfoSerializer(serializers.ModelSerializer):
    enterpises = EnterpriseModelSerializer(label='公司', many=True, read_only=True)
    labels = LabelsModelSerializer(label='标签', many=True, read_only=True)
    questions = QuestionSerializer(label='用户收藏的问题', many=True, read_only=True)
    answer_question = serializers.SerializerMethodField()
    collected_articles = CollectSerializer(label='用户收藏的文章', many=True, read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'realname', 'birthday', 'sex', 'avatar',
                  'website', 'email', 'city', 'address', 'labels', 'questions',
                  'collected_articles', 'answer_question', 'enterpises')
    def get_answer_question(self,obj):
        instance = obj.replies.filter(parent__isnull=True)
        return QuestionAnswerSerializer(instance,many=True,read_only=True).data


class UserLabelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"








